package com.urerp.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.urerp.web.common.SessionUtil;
import com.urerp.web.persistence.CodeMapper;
import com.urerp.web.persistence.ProductMapper;

@Controller
public class ProductController {
	
	private static final Logger logger = LogManager.getLogger(ProductController.class);
	
	@Autowired
	private CodeMapper codeMapper;
	
	@Autowired
	private ProductMapper productMapper;
	
	// 프로퍼티 파일 읽기
	@Value("#{code['product.type']}") 			private String m_type;
	@Value("#{code['product.color']}") 			private String m_color;
	@Value("#{code['product.size']}") 			private String m_size;
	
	
	// 상품 리스트
    @RequestMapping(value = "/product/list")
	public String list(Model model) {
    	
    	logger.debug("RequestMapping : /product/list, Method : list");
    	
    	model.addAttribute("prdTypeList", codeMapper.getGroupCodeList(m_type));
    	model.addAttribute("prdColorList", codeMapper.getGroupCodeList(m_color));
    	model.addAttribute("prdSizeList", codeMapper.getGroupCodeList(m_size));
    	
    	return "/product/list";
    }
    
    // 상품 리스트 데이터
    @RequestMapping(value = "/product/listData", method = RequestMethod.GET, produces = "application/json; charset=utf8")
	public @ResponseBody HashMap<String, Object> listData(Model model, @RequestParam HashMap<String, Object> tableMap) {
    	
    	logger.debug("RequestMapping : /product/listData, Method : listData");
    	
    	if (tableMap != null) {
    		tableMap.put("M_TYPE", 		m_type);
    		tableMap.put("M_COLOR", 	m_color);
    		tableMap.put("M_SIZE", 		m_size);
    	}
    	
    	tableMap.put("order_by", tableMap.get("mDataProp_" + tableMap.get("iSortCol_0")) + " " + tableMap.get("sSortDir_0"));

    	ArrayList<LinkedHashMap<String, String>> list = productMapper.getProductList(tableMap);
    	
    	tableMap.put("sEcho", 					Integer.parseInt((String) tableMap.get("sEcho")));
    	tableMap.put("iTotalRecords", 			productMapper.getProductListCount(tableMap));
    	tableMap.put("iTotalDisplayRecords", 	tableMap.get("iTotalRecords"));
    	tableMap.put("aaData", 					list);

    	return tableMap;
    }
    
    // 상품 등록 폼
	@RequestMapping(value = "/product/registerForm")
    public String registerForm(Model model) {
		
		logger.debug("RequestMapping : /product/registerForm, Method : registerForm");
		
		model.addAttribute("prdTypeList", 	codeMapper.getGroupCodeList(m_type));
		model.addAttribute("prdColorList", 	codeMapper.getGroupCodeList(m_color));
		model.addAttribute("prdSizeList", 	codeMapper.getGroupCodeList(m_size));
		
		return "product/register_form";
        
	}
	
	 // 상품 상세(수정) 폼
    @RequestMapping(value = "/product/modifyForm", method = RequestMethod.POST)
	public String modifyForm(Model model, @RequestParam String prd_id) {
    	
    	logger.debug("RequestMapping : /product/modifyForm, Method : modifyForm");
    	
    	model.addAttribute("prdTypeList", 	codeMapper.getGroupCodeList(m_type));
		model.addAttribute("prdColorList", 	codeMapper.getGroupCodeList(m_color));
		model.addAttribute("prdSizeList", 	codeMapper.getGroupCodeList(m_size));
    	
		model.addAttribute("productMap", productMapper.getProduct(prd_id));
    	
    	return "product/register_form";
    }
	
	// 상품 등록/수정 (DB Insert/Update)
    @RequestMapping(value = {"/product/submitRegister","/product/submitModify"}, method = RequestMethod.POST, produces = "application/json; charset=utf8")
    public synchronized @ResponseBody String submit(Model model, HttpServletRequest request, @RequestParam HashMap<String, String> productMap) {
    	
    	logger.debug("RequestMapping : {}, Method : submit", request.getServletPath());
    	
    	/*
    	 * 오류코드
    	 * 0 - success
    	 * 9 - no data
    	 * 1 - db insert / update failed
    	 * 8 - exception
    	 */
    	
    	if (productMap == null) {
    		return "9";
    	}
    	
    	int result = 0;
    	
    	// 등록(수정)자 가져와서 넣기
    	productMap.put("prd_unit_price", productMap.get("prd_unit_price").replaceAll(",", ""));
    	
    	if (productMap.get("docu_type").equals("W")) {
    		
    		productMap.put("reg_user", SessionUtil.getMemberSession("USER_ID"));
    		
    		result = productMapper.setProduct(productMap);
    		
    	} else if (productMap.get("docu_type").equals("M")) {
    		productMap.put("upd_user", SessionUtil.getMemberSession("USER_ID"));
    		
    		result = productMapper.updateProduct(productMap);
    	}
    	
    	try {
    		
    		if (result != 1) {
    			
    			return "1";
    		}
    		
    	} catch (Exception e) {
    		logger.debug("setProduct : Insert or Modify Fail - {}", e.getMessage());
    		
    		return "8";
    	}
    	
    	return "0";
    }
    
    // 상품 검색 폼
 	@RequestMapping(value = "/product/searchPopup")
 	public String searchPopup(Model model) {
     	
     	logger.debug("RequestMapping : /product/searchPopup, Method : searchPopup");
     	
     	
     	return "product/search_pop";
     }
	 
}
